package com.lanvideo.service;

import com.lanvideo.entity.User;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 会话管理服务
 */
@Service
public class SessionService {
    
    // 在线用户统计
    private final AtomicInteger onlineUserCount = new AtomicInteger(0);
    
    // 用户会话映射（用于快速查找）
    private final ConcurrentHashMap<String, HttpSession> userSessions = new ConcurrentHashMap<>();
    
    // 用户登录状态映射
    private final ConcurrentHashMap<Integer, String> userLoginStatus = new ConcurrentHashMap<>();

    /**
     * 用户登录时调用
     */
    public void onUserLogin(User user, HttpSession session) {
        String sessionId = session.getId();
        Integer userId = user.getId();
        
        // 如果用户已经在其他地方登录，踢出之前的会话
        String existingSessionId = userLoginStatus.get(userId);
        if (existingSessionId != null && !existingSessionId.equals(sessionId)) {
            HttpSession existingSession = userSessions.get(existingSessionId);
            if (existingSession != null) {
                existingSession.invalidate();
                userSessions.remove(existingSessionId);
            }
        }
        
        // 记录新会话
        userSessions.put(sessionId, session);
        userLoginStatus.put(userId, sessionId);
        onlineUserCount.incrementAndGet();
        
        // 设置会话属性
        session.setAttribute("loginTime", System.currentTimeMillis());
        session.setAttribute("lastAccessTime", System.currentTimeMillis());
    }

    /**
     * 用户登出时调用
     */
    public void onUserLogout(HttpSession session) {
        String sessionId = session.getId();
        User user = (User) session.getAttribute("user");
        
        if (user != null) {
            userLoginStatus.remove(user.getId());
        }
        
        userSessions.remove(sessionId);
        onlineUserCount.decrementAndGet();
    }

    /**
     * 更新用户最后访问时间
     */
    public void updateLastAccessTime(HttpSession session) {
        session.setAttribute("lastAccessTime", System.currentTimeMillis());
    }

    /**
     * 检查用户是否在线
     */
    public boolean isUserOnline(Integer userId) {
        return userLoginStatus.containsKey(userId);
    }

    /**
     * 获取在线用户数量
     */
    public int getOnlineUserCount() {
        return onlineUserCount.get();
    }

    /**
     * 获取用户会话
     */
    public HttpSession getUserSession(Integer userId) {
        String sessionId = userLoginStatus.get(userId);
        if (sessionId != null) {
            return userSessions.get(sessionId);
        }
        return null;
    }

    /**
     * 强制用户下线
     */
    public boolean forceUserLogout(Integer userId) {
        String sessionId = userLoginStatus.get(userId);
        if (sessionId != null) {
            HttpSession session = userSessions.get(sessionId);
            if (session != null) {
                session.invalidate();
                userSessions.remove(sessionId);
                userLoginStatus.remove(userId);
                onlineUserCount.decrementAndGet();
                return true;
            }
        }
        return false;
    }

    /**
     * 清理无效会话
     */
    public void cleanupInvalidSessions() {
        userSessions.entrySet().removeIf(entry -> {
            HttpSession session = entry.getValue();
            try {
                // 尝试访问会话，如果无效会抛出异常
                session.getAttribute("user");
                return false; // 会话有效，不移除
            } catch (IllegalStateException e) {
                // 会话无效，移除
                User user = (User) session.getAttribute("user");
                if (user != null) {
                    userLoginStatus.remove(user.getId());
                }
                onlineUserCount.decrementAndGet();
                return true;
            }
        });
    }
}
